package com.sen.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.sen.model.entity.BmsPost;
import com.sen.model.entity.BmsTag;
import com.sen.mapper.BmsTagMapper;
import com.sen.service.BmsPostService;
import com.sen.service.BmsPostTagService;
import com.sen.service.BmsTagService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Repository;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.FormatFlagsConversionMismatchException;
import java.util.List;
import java.util.Set;

/**
 * <p>
 * 标签表 服务实现类
 * </p>
 *
 * @author ergou
 * @since 2021-04-12
 */
@Service
public class BmsTagServiceImpl extends ServiceImpl<BmsTagMapper, BmsTag> implements BmsTagService {

    @Resource
    private BmsPostTagService bmsPostTagService;
    @Resource
    private BmsPostService bmsPostService;

    @Override
    public List<BmsTag> insertTags(List<String> tagNames) {
        List<BmsTag> tagList = new ArrayList<>();
        for (String tagName : tagNames) {
            BmsTag tag = this.baseMapper.selectOne(new LambdaQueryWrapper<BmsTag>().eq(BmsTag::getName,tagName));

            //如果数据库中没有，新标签 则插入
            if (tag == null){
                tag = BmsTag.builder().name(tagName).build();
                this.baseMapper.insert(tag);
            }else {
                tag.setTopicCount(tag.getTopicCount()+1);
                this.baseMapper.updateById(tag);
            }
            tagList.add(tag);

        }
        return tagList;
    }

    @Override
    public Page<BmsPost> selectTopicsByTagId(Page<BmsPost> topicPage, String id) {

        // 获取关联的话题ID
        Set<String> ids = bmsPostTagService.selectTopicIdsByTagId(id);
        LambdaQueryWrapper<BmsPost> wrapper = new LambdaQueryWrapper<>();
        wrapper.in(BmsPost::getId, ids);

        return bmsPostService.page(topicPage, wrapper);
    }
}
